/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useCallback, useEffect } from 'react';
import { connect } from 'dva';
import { Button, Form, Input, Table, Select, Popconfirm } from 'antd';

const FormItem = Form.Item;
const { Option } = Select;

const ScanType = props => {
  const {
    dispatch,
    form,
    scanTypesList,
    scanOptionList,
    userInfo = {},
    options: { key },
  } = props;
  const isZyAccount = key == 'post';
  const { branchId } = userInfo;
  const zyPayload = isZyAccount ? { branch_id: branchId } : {};
  const { getFieldDecorator, validateFields } = form;

  useEffect(() => {
    getList();
  }, []);

  const getList = (payload = {}) => {
    dispatch({
      type: 'scan/getScanTypesList',
      payload: {
        ...zyPayload,
        ...payload,
      },
    });
  };

  const add = () => {
    validateFields((err, fieldsValue) => {
      if (err) return;
      dispatch({
        type: 'scan/addScanType',
        payload: {
          ...fieldsValue,
          ...zyPayload,
        },
      }).then(() => {
        form.resetFields();
        getList();
      });
    });
  };

  const deleteType = useCallback(id => {
    dispatch({
      type: 'scan/deleteScanType',
      payload: {
        id,
        ...zyPayload,
      },
    }).then(() => {
      getList();
    });
  }, []);

  const onDropDown = useCallback(visible => {
    if (visible) {
      dispatch({
        type: 'scan/getScanOptionList',
        payload: zyPayload,
      });
    }
  }, []);

  const columns = [
    {
      title: '扫描类型',
      dataIndex: 'scan_type',
      align: 'center',
    },
    {
      title: '扫描类型选项',
      dataIndex: 'scan_option',
      align: 'center',
    },
    {
      title: '操作',
      align: 'center',
      render: (text, record) => (
        <Popconfirm title="确定删除该数据？" onConfirm={() => deleteType(record.id)}>
          <a>删除</a>
        </Popconfirm>
      ),
    },
  ];

  return (
    <div>
      <Form layout="inline">
        <FormItem>
          {getFieldDecorator('scanType', {
            rules: [
              {
                required: true,
                message: '请输入自定义的扫描类型',
              },
              {
                max: 10,
                message: '请输入10个字符以内的中文英文或数字',
              },
              {
                pattern: /[\u4e00-\u9fa5_a-zA-Z0-9_]+$/,
                message: '请输入中文英文或数字',
              },
            ],
          })(<Input allowClear style={{ width: 300 }} placeholder="请输入自定义的扫描类型" />)}
        </FormItem>
        <FormItem>
          {getFieldDecorator('scanOption')(
            <Select
              onDropdownVisibleChange={onDropDown}
              placeholder="请选择扫描类型选项（可选项）"
              style={{ width: 300 }}
              allowClear
            >
              {scanOptionList.map(val => (
                <Option key={val} value={val}>
                  {val}
                </Option>
              ))}
            </Select>,
          )}
        </FormItem>
        <FormItem>
          <Button type="primary" onClick={add}>
            添加
          </Button>
        </FormItem>
      </Form>
      <Table dataSource={scanTypesList} columns={columns} rowKey="id" pagination={false} />
    </div>
  );
};

export default connect(({ loading, scan, user, setting }) => ({
  scanTypesList: scan.scanTypesList,
  scanOptionList: scan.scanOptionList,
  loading: loading.effects['scan/getScanTypesList'],
  userInfo: user.currentUser.user_info,
  ...setting,
}))(Form.create()(React.memo(ScanType)));
